package com.example.websocketclusterspringbootstarter.job;

import com.alibaba.fastjson.JSON;
import com.corundumstudio.socketio.SocketIOClient;
import com.example.websocketclusterspringbootstarter.event.BaseEventWrapper;
import com.example.websocketclusterspringbootstarter.handler.EventHandler;
import com.example.websocketclusterspringbootstarter.properties.RedisTemplateProperties;
import com.example.websocketclusterspringbootstarter.utils.EventHandlerUtil;
import com.example.websocketclusterspringbootstarter.utils.LocalCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 拉取msg任务
 *
 * @author zhucc
 * @date 2022-03-08
 */
@Slf4j
@Component
public class PullMsgJob implements InitializingBean {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private RedisTemplateProperties redisTemplateProperties;

    @Value("${nodeName}")
    private String nodeName;

    @Override
    public void afterPropertiesSet() {
        Runnable runnable = () -> {
            while (true) {
                String pullMsg = redisTemplate.opsForList().rightPop(nodeName);
                if (pullMsg == null) {
                    try {
                        Thread.sleep(redisTemplateProperties.getInterval());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    BaseEventWrapper baseEventWrapper = JSON.parseObject(pullMsg, BaseEventWrapper.class);
                    try {
                        log.info("###执行任务###内容={}", JSON.toJSONString(baseEventWrapper));
                        SocketIOClient localClient = LocalCacheUtil.getLocalClient(baseEventWrapper.getTo());
                        if (null != localClient) {
                            EventHandler handler = EventHandlerUtil.getHandler(baseEventWrapper.getEventName());
                            handler.doHandle(localClient, baseEventWrapper);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable, "拉取队列msg线程nodeName=" + "systemProperty.getNodeName()");
        thread.setDaemon(true);
        thread.start();
    }
}
